﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Net;

namespace MultiDAQ_Analysis.Util
{
    public static class AppConfig
    {
        public static int ChannelCount
        {
            get
            {
                string value = ConfigurationManager.AppSettings["ChannelCount"];
                if (int.TryParse(value, out int count) && count > 0)
                {
                    return count;
                }
                return 4; // 默认通道数量
            }
        }
        public static int UdpListenPort =>
          int.TryParse(ConfigurationManager.AppSettings["UdpListenPort"], out var port) ? port : 5000;

        public static IPAddress UdpRemoteIP =>
            IPAddress.TryParse(ConfigurationManager.AppSettings["UdpRemoteIP"], out var ip) ? ip : IPAddress.Loopback;

        public static int UdpRemotePort =>
            int.TryParse(ConfigurationManager.AppSettings["UdpRemotePort"], out var port) ? port : 5001;

        // DAC设置
        public static double DACVoltage =>
            double.TryParse(ConfigurationManager.AppSettings["DACVoltage"], out var voltage) ? voltage : 0.0;

        public static double PlotXStep
        {
            get
            {
                string value = ConfigurationManager.AppSettings["PlotXStep"];
                return double.TryParse(value, out var step) && step > 0 ? step : 1.0;
            }
        }

        public static int LogPrint =>
    int.TryParse(ConfigurationManager.AppSettings["LogPrint"], out var LogPrint) ? LogPrint : 0;


        // 可扩展更多配置项


        // 新增：统一的通道颜色定义
        public static Color[] ChannelColors = new Color[]
        {
        Color.FromArgb(144, 238, 144), // 浅绿色 (对应OxyColors.LimeGreen)
        Color.FromArgb(30, 144, 255),  // 蓝色 (对应OxyColors.DodgerBlue)
        Color.FromArgb(220, 20, 60),   // 深红色 (对应OxyColors.Crimson)
        Color.FromArgb(255, 165, 0),   // 橙色 (对应OxyColors.Orange)
        Color.FromArgb(128, 0, 128),   // 紫色 (对应OxyColors.Purple)
        Color.FromArgb(0, 128, 128),   // 青绿色 (对应OxyColors.Teal)
        Color.FromArgb(165, 42, 42),   // 棕色 (对应OxyColors.Brown)
        Color.FromArgb(255, 105, 180)  // 粉色 (对应OxyColors.HotPink)
        };
        // 新增：获取OxyColor格式的通道颜色
        public static OxyPlot.OxyColor[] GetOxyChannelColors()
        {
            return new OxyPlot.OxyColor[]
            {
            OxyPlot.OxyColors.LimeGreen,
            OxyPlot.OxyColors.DodgerBlue,
            OxyPlot.OxyColors.Crimson,
            OxyPlot.OxyColors.Orange,
            OxyPlot.OxyColors.Purple,
            OxyPlot.OxyColors.Teal,
            OxyPlot.OxyColors.Brown,
            OxyPlot.OxyColors.HotPink
            };
        }
        public static string Theme => ConfigurationManager.AppSettings["Theme"] ?? "Light";


        
            // ... 现有代码保持不变 ...

            #region 水样品配置

            public static string WaterSampleName =>
                ConfigurationManager.AppSettings["WaterSampleName"] ?? "";

            public static string WaterSampleNumber =>
                ConfigurationManager.AppSettings["WaterSampleNumber"] ?? "";

            public static string WaterSampler =>
                ConfigurationManager.AppSettings["WaterSampler"] ?? "";

            public static string WaterSampleLocation =>
                ConfigurationManager.AppSettings["WaterSampleLocation"] ?? "";

            public static string WaterMeasurer =>
                ConfigurationManager.AppSettings["WaterMeasurer"] ?? "";

            public static double WaterVolume =>
                double.TryParse(ConfigurationManager.AppSettings["WaterVolume"], out var value) ? value : 20.0;

            public static double WaterTotalResidue =>
                double.TryParse(ConfigurationManager.AppSettings["WaterTotalResidue"], out var value) ? value : 10.0;

            public static double WaterTestedSample =>
                double.TryParse(ConfigurationManager.AppSettings["WaterTestedSample"], out var value) ? value : 30.0;

            #endregion

            #region 生物样品配置

            public static string BioSampleName =>
                ConfigurationManager.AppSettings["BioSampleName"] ?? "";

            public static string BioSampleNumber =>
                ConfigurationManager.AppSettings["BioSampleNumber"] ?? "";

            public static string BioSampler =>
                ConfigurationManager.AppSettings["BioSampler"] ?? "";

            public static string BioSampleLocation =>
                ConfigurationManager.AppSettings["BioSampleLocation"] ?? "";

            public static string BioMeasurer =>
                ConfigurationManager.AppSettings["BioMeasurer"] ?? "";

            public static double BioFreshWeight =>
                double.TryParse(ConfigurationManager.AppSettings["BioFreshWeight"], out var value) ? value : 20.0;

            public static double BioTestedSample =>
                double.TryParse(ConfigurationManager.AppSettings["BioTestedSample"], out var value) ? value : 10.0;

            public static double BioTotalAsh =>
                double.TryParse(ConfigurationManager.AppSettings["BioTotalAsh"], out var value) ? value : 30.0;

            public static double BioRecoveryRate =>
                double.TryParse(ConfigurationManager.AppSettings["BioRecoveryRate"], out var value) ? value : 85.0;

            #endregion

            #region 气体样品配置

            public static string GasSampleName =>
                ConfigurationManager.AppSettings["GasSampleName"] ?? "";

            public static string GasSampleNumber =>
                ConfigurationManager.AppSettings["GasSampleNumber"] ?? "";

            public static string GasSampler =>
                ConfigurationManager.AppSettings["GasSampler"] ?? "";

            public static string GasSampleLocation =>
                ConfigurationManager.AppSettings["GasSampleLocation"] ?? "";

            public static string GasMeasurer =>
                ConfigurationManager.AppSettings["GasMeasurer"] ?? "";

            public static double GasSampleVolume =>
                double.TryParse(ConfigurationManager.AppSettings["GasSampleVolume"], out var value) ? value : 20.0;

            public static double GasFilterEfficiency =>
                double.TryParse(ConfigurationManager.AppSettings["GasFilterEfficiency"], out var value) ? value : 10.0;

            public static double GasAbsorptionFactor =>
                double.TryParse(ConfigurationManager.AppSettings["GasAbsorptionFactor"], out var value) ? value : 30.0;

            #endregion

            #region 环境样品配置

            public static string EnvSampleName =>
                ConfigurationManager.AppSettings["EnvSampleName"] ?? "";

            public static string EnvSampleNumber =>
                ConfigurationManager.AppSettings["EnvSampleNumber"] ?? "";

            public static string EnvSampler =>
                ConfigurationManager.AppSettings["EnvSampler"] ?? "";

            public static string EnvSampleLocation =>
                ConfigurationManager.AppSettings["EnvSampleLocation"] ?? "";

            public static string EnvMeasurer =>
                ConfigurationManager.AppSettings["EnvMeasurer"] ?? "";

            public static double EnvSampleMass =>
                double.TryParse(ConfigurationManager.AppSettings["EnvSampleMass"], out var value) ? value : 20.0;

        #endregion


        #region 配置保存方法

        /// <summary>
        /// 保存水样品基本信息到配置文件
        /// </summary>
        public static bool SaveWaterSampleInfo(string name, string number, string sampler,
                                             string location, string measurer,
                                             double volume, double totalResidue, double testedSample)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                SetAppSetting(config, "WaterSampleName", name);
                SetAppSetting(config, "WaterSampleNumber", number);
                SetAppSetting(config, "WaterSampler", sampler);
                SetAppSetting(config, "WaterSampleLocation", location);
                SetAppSetting(config, "WaterMeasurer", measurer);
                SetAppSetting(config, "WaterVolume", volume.ToString());
                SetAppSetting(config, "WaterTotalResidue", totalResidue.ToString());
                SetAppSetting(config, "WaterTestedSample", testedSample.ToString());

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存水样品配置失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 保存生物样品基本信息到配置文件
        /// </summary>
        public static bool SaveBioSampleInfo(string name, string number, string sampler,
                                           string location, string measurer,
                                           double freshWeight, double testedSample, double totalAsh, double recoveryRate)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                SetAppSetting(config, "BioSampleName", name);
                SetAppSetting(config, "BioSampleNumber", number);
                SetAppSetting(config, "BioSampler", sampler);
                SetAppSetting(config, "BioSampleLocation", location);
                SetAppSetting(config, "BioMeasurer", measurer);
                SetAppSetting(config, "BioFreshWeight", freshWeight.ToString());
                SetAppSetting(config, "BioTestedSample", testedSample.ToString());
                SetAppSetting(config, "BioTotalAsh", totalAsh.ToString());
                SetAppSetting(config, "BioRecoveryRate", recoveryRate.ToString());

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存生物样品配置失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 保存气体样品基本信息到配置文件
        /// </summary>
        public static bool SaveGasSampleInfo(string name, string number, string sampler,
                                           string location, string measurer,
                                           double sampleVolume, double filterEfficiency, double absorptionFactor)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                SetAppSetting(config, "GasSampleName", name);
                SetAppSetting(config, "GasSampleNumber", number);
                SetAppSetting(config, "GasSampler", sampler);
                SetAppSetting(config, "GasSampleLocation", location);
                SetAppSetting(config, "GasMeasurer", measurer);
                SetAppSetting(config, "GasSampleVolume", sampleVolume.ToString());
                SetAppSetting(config, "GasFilterEfficiency", filterEfficiency.ToString());
                SetAppSetting(config, "GasAbsorptionFactor", absorptionFactor.ToString());

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存气体样品配置失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 保存环境样品基本信息到配置文件
        /// </summary>
        public static bool SaveEnvSampleInfo(string name, string number, string sampler,
                                           string location, string measurer, double sampleMass)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                SetAppSetting(config, "EnvSampleName", name);
                SetAppSetting(config, "EnvSampleNumber", number);
                SetAppSetting(config, "EnvSampler", sampler);
                SetAppSetting(config, "EnvSampleLocation", location);
                SetAppSetting(config, "EnvMeasurer", measurer);
                SetAppSetting(config, "EnvSampleMass", sampleMass.ToString());

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存环境样品配置失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 批量保存配置项
        /// </summary>
        public static bool SaveMultipleSettings(Dictionary<string, string> settings)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                foreach (var setting in settings)
                {
                    SetAppSetting(config, setting.Key, setting.Value);
                }

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"批量保存配置失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 设置或更新AppSettings中的配置项
        /// </summary>
        private static void SetAppSetting(Configuration config, string key, string value)
        {
            if (config.AppSettings.Settings[key] != null)
            {
                config.AppSettings.Settings[key].Value = value;
            }
            else
            {
                config.AppSettings.Settings.Add(key, value);
            }
        }

        /// <summary>
        /// 重新加载配置（强制刷新ConfigurationManager缓存）
        /// </summary>
        public static void RefreshConfiguration()
        {
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 获取所有水样品配置项
        /// </summary>
        public static Dictionary<string, string> GetAllWaterSampleSettings()
        {
            return new Dictionary<string, string>
            {
                ["WaterSampleName"] = WaterSampleName,
                ["WaterSampleNumber"] = WaterSampleNumber,
                ["WaterSampler"] = WaterSampler,
                ["WaterSampleLocation"] = WaterSampleLocation,
                ["WaterMeasurer"] = WaterMeasurer,
                ["WaterVolume"] = WaterVolume.ToString(),
                ["WaterTotalResidue"] = WaterTotalResidue.ToString(),
                ["WaterTestedSample"] = WaterTestedSample.ToString()
            };
        }

        /// <summary>
        /// 获取所有生物样品配置项
        /// </summary>
        public static Dictionary<string, string> GetAllBioSampleSettings()
        {
            return new Dictionary<string, string>
            {
                ["BioSampleName"] = BioSampleName,
                ["BioSampleNumber"] = BioSampleNumber,
                ["BioSampler"] = BioSampler,
                ["BioSampleLocation"] = BioSampleLocation,
                ["BioMeasurer"] = BioMeasurer,
                ["BioFreshWeight"] = BioFreshWeight.ToString(),
                ["BioTestedSample"] = BioTestedSample.ToString(),
                ["BioTotalAsh"] = BioTotalAsh.ToString(),
                ["BioRecoveryRate"] = BioRecoveryRate.ToString()
            };
        }

        /// <summary>
        /// 获取所有气体样品配置项
        /// </summary>
        public static Dictionary<string, string> GetAllGasSampleSettings()
        {
            return new Dictionary<string, string>
            {
                ["GasSampleName"] = GasSampleName,
                ["GasSampleNumber"] = GasSampleNumber,
                ["GasSampler"] = GasSampler,
                ["GasSampleLocation"] = GasSampleLocation,
                ["GasMeasurer"] = GasMeasurer,
                ["GasSampleVolume"] = GasSampleVolume.ToString(),
                ["GasFilterEfficiency"] = GasFilterEfficiency.ToString(),
                ["GasAbsorptionFactor"] = GasAbsorptionFactor.ToString()
            };
        }

        /// <summary>
        /// 获取所有环境样品配置项
        /// </summary>
        public static Dictionary<string, string> GetAllEnvSampleSettings()
        {
            return new Dictionary<string, string>
            {
                ["EnvSampleName"] = EnvSampleName,
                ["EnvSampleNumber"] = EnvSampleNumber,
                ["EnvSampler"] = EnvSampler,
                ["EnvSampleLocation"] = EnvSampleLocation,
                ["EnvMeasurer"] = EnvMeasurer,
                ["EnvSampleMass"] = EnvSampleMass.ToString()
            };
        }

        /// <summary>
        /// 获取所有DAC配置项
        /// </summary>
        public static Dictionary<string, string> GetAllDACSettings()
        {
            return new Dictionary<string, string>
            {
                ["DACVoltage"] = DACVoltage.ToString()
            };
        }

        /// <summary>
        /// 保存DAC设置到配置文件
        /// </summary>
        public static bool SaveDACSettings(double dacVoltage)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                SetAppSetting(config, "DACVoltage", dacVoltage.ToString());

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存DAC配置失败: {ex.Message}");
                return false;
            }
        }



        #endregion
    }
}
